import React from 'react';
import {
    ScrollView,
    View,
    Text,
    InteractionManager,
    TouchableOpacity,
    Image,
    Dimensions,
    TextInput,
    KeyboardAvoidingView,
    Platform
} from 'react-native';

import {connect} from 'react-redux';

import {getShopInfo, changeShopInfo, getAuthInfo} from './actions';
import {NativeUtil, toast} from '../../utils/NativeUtil';
import NetUtil from '../../common/NetUtil';
import config from '../../config/config';
import CLNavigatorHeader from '../../component/CLNavigatorHeader';
import backIcon from '../../image/back.png';
import commonStyles from '../../styles/commonstyles';
import {getQiniuToken} from '../../utils/commonHttp';
import {chooseImage, chooseLocation} from '../../utils/NativeUtil';
import ActionSheet from 'react-native-actionsheet';

import {naviPush, naviBack} from '../../navigatorApp/actions'
import commonstyles from '../../styles/commonstyles';
import { GET_AUTH_INFO } from './constants';
import { gotoCert } from '../main/actions';

class Shop extends React.Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        header: <CLNavigatorHeader navigation={navigation} title="店铺信息"/>,
    });

    constructor(props) {
        super(props);

        this.imgType = 0;
    }

    componentDidMount() {
        InteractionManager.runAfterInteractions(() => {
            this.props.getShopInfo(this.props.token);
            this.props.getAuthInfo(this.props.token);
        });
    }

    _backToFront() {
        this.props.naviBack();
    }

    toastmessage(message) {
        toast(message);
    }

    showLoading(message) {

    }

    hideLoading() {

    }

    showActionSheet(type) {
        this.imgType = type
        this.ActionSheet.show()
    }

    handlePress = (i) => {
        if (i == 1) {
            this.chooseImg('takephoto');
        } else if (i == 2) {
            this.chooseImg('choose');
        }
    };

    chooseImg = (type) => {
        var self = this;
        getQiniuToken(function (res) {
            let qntoken = res.token;

            let params = {};
            if (this.imgType == 1) {
                params = {
                    type: type,
                    size_w: 5,
                    size_h: 4,
                    token: qntoken,
                    filetag: 'shop'
                };
            } else {
                params = {
                    type: type,
                    size_w: 1,
                    size_h: 1,
                    token: qntoken,
                    filetag: 'shop'
                };
            }

            chooseImage(params, function (res) {
                if (this.imgType == 1) {
                    self.props.changeShopInfo({shopBackgroundImg: config.qiniuUrl + res.imgs});
                } else {
                    self.props.changeShopInfo({shoplogo: config.qiniuUrl + res.imgs});
                }
            });

        }, function (message) {
            alert(message);
        })
    };

    chooseLocation() {
        let self = this;
        if (this.lng == undefined) {
            this.lng = this.props.lng;
        }
        if (this.lat == undefined) {
            this.lat = this.props.lat;
        }
        chooseLocation({lat: this.lat, lon: this.lng}, (res) => {
            self.lat = res.lat.toString();
            self.lng = res.lon.toString();
        });
    }

    save() {
        if (this.props.shopName == '') {
            this.toastmessage('店名不能为空');
            return;
        }

        if (this.props.phone == '') {
            this.toastmessage('联系电话不能为空');
            return;
        }

        if (this.props.address == '') {
            this.toastmessage('详细地址不能为空');
            return;
        }

        if (this.lng == undefined) {
            this.lng = this.props.lng;
        }
        if (this.lat == undefined) {
            this.lat = this.props.lat;
        }

        const params = {
            token: this.props.token,
            shopName: this.props.shopName,
            phone: this.props.phone,
            address: this.props.address,
            logo: this.props.shoplogo,
            backgroundImg: this.props.shopBackgroundImg,
            lng: this.lng,
            lat: this.lat,
        };

        let url = '/s/shop/update';

        this.showLoading('正在更新');
        var self = this;
        NetUtil.postSign(config.apiUrl + url, params, function (res) {
            self.hideLoading()
            if (res.success) {
                self._backToFront();
                self.toastmessage("更新成功");
            } else {
                self.toastmessage(res.message);
            }
        });
    }

    auth = () => {
        this.props.gotoCert(false);
        this.props.naviPush('shopAuth')
    }

    render() {
        let {width, height} = Dimensions.get('window');
        let imageView = undefined;
        if (this.props.shopBackgroundImg == "" || this.props.shopBackgroundImg == undefined) {
            imageView =
                <View style={{width: width, height: width / 5.0 * 4.0, justifyContent: 'center', alignItems: "center"}}><Text>上传门店照片</Text></View>
        } else {
            imageView = <Image source={{uri: this.props.shopBackgroundImg}} style={{width: width, height: width / 5.0 * 4.0}}/>
        }

        let positionResult = '未选';
        if (this.props.lng != undefined && this.props.lng != '') {
            positionResult = '已选';
        }

        let authResult = undefined;
        if (this.props.auditStatus == -1) {
            authResult = '未认证';
        } else if (this.props.auditStatus == -2) {
            authResult = '重新认证';
        } else if (this.props.auditStatus == 0) {
            authResult = '认证中';
        } else if (this.props.auditStatus == 1) {
            authResult = '已认证';
        } else {
            authResult = '';
        }
        let authAction = undefined;
        if (this.props.auditStatus < 0) {
            authAction = this.auth;
        }
        return (
            <View style={{flex: 1, flexDirection: 'column', backgroundColor: '#ebebeb'}}>
                <KeyboardAvoidingView behavior={(Platform.OS === 'ios') ? 'padding' : ''}
                                      keyboardVerticalOffset={ 64 }>
                    <ScrollView>
                        <TouchableOpacity
                            underlayColor='rgba(255,255,255,0)'
                            onPress={() => this.showActionSheet(1)}
                        >
                            {imageView}
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.showActionSheet(2)}>
                        <View style={{marginTop: 1,
                                      flexDirection: 'row', 
                                      alignItems: "center", 
                                      backgroundColor: "white", 
                                      justifyContent: 'space-between', 
                                      paddingRight: 10, 
                                      height: 70
                                    }}>
                            <Text
                                style={{
                                    fontSize: 16,
                                    marginLeft: 10
                                }}>店铺logo</Text>
                            <Image
                                style={{
                                    width: 60,
                                    height: 60
                                }}
                                source={{
                                    uri: this.props.shoplogo
                                }}/>
                        </View>
                    </TouchableOpacity>
                    <View style={commonStyles.line_gray}/>
                        <TextInput
                            style={{
                                backgroundColor: 'white',
                                flex: 1,
                                alignItems: 'flex-end',
                                justifyContent: 'flex-end',
                                paddingLeft: 10,
                                width: width,
                                height: 48
                            }}
                            placeholder='店铺名称(20以内汉字,字母,数字,下划线)'
                            value={this.props.shopName}
                            underlineColorAndroid={'transparent'}
                            // editable={false}
                            textAlign='left'
                            writingDirection='rtl'
                            onChangeText={(text) => this.props.changeShopInfo({shopName: text})}
                            returnKeyType='done'
                            multiline={false}
                        />
                        <View style={commonStyles.line_gray}/>
                        <TextInput
                            style={{
                                backgroundColor: 'white',
                                flex: 1,
                                alignItems: 'flex-end',
                                justifyContent: 'flex-end',
                                paddingLeft: 10,
                                width: width,
                                height: 48
                            }}
                            placeholder='联系电话'
                            value={this.props.phone}
                            underlineColorAndroid={'transparent'}
                            textAlign='left'
                            writingDirection='rtl'
                            onChangeText={(text) => this.props.changeShopInfo({phone: text})}
                            returnKeyType='done'
                            multiline={false}
                        />
                        <View style={commonStyles.line_gray}/>
                        <TouchableOpacity style={{flex: 1}} 
                            onPress={authAction}>
                            <View style={[commonStyles.itembar, {paddingLeft: 10, paddingRight: 10}]}>
                                <Text>实名认证</Text>
                                <View style={commonstyles.itembarRight}>
                                    <Text>{authResult}</Text>
                                    <Image style={{width: 20, height: 15}} source={require('../../image/img_right_grey.png')}/>
                                </View>
                            </View>
                        </TouchableOpacity>
                        {/* <View style={commonStyles.line_gray}/> */}
                        {/* <TextInput
                            style={{
                                backgroundColor: 'white',
                                flex: 1,
                                alignItems: 'flex-end',
                                justifyContent: 'flex-end',
                                paddingLeft: 10,
                                width: width,
                                height: 48
                            }}
                            placeholder='品牌'
                            value={this.props.brand}
                            underlineColorAndroid={'transparent'}
                            editable={false}
                            textAlign='left'
                            writingDirection='rtl'
                            onChangeText={(text) => this.props.changeShopInfo({brand: text})}
                            returnKeyType='done'
                            multiline={false}
                        /> */}
                        <View style={[commonStyles.line_gray, {marginTop: 10}]}/>
                        <TextInput
                            style={{
                                backgroundColor: 'white',
                                flex: 1,
                                alignItems: 'flex-end',
                                justifyContent: 'flex-end',
                                paddingLeft: 10,
                                width: width,
                                height: 48
                            }}
                            placeholder='所在地区'
                            value={this.props.cityName}
                            underlineColorAndroid={'transparent'}
                            editable={false}
                            textAlign='left'
                            writingDirection='rtl'
                            onChangeText={(text) => this.props.changeShopInfo({cityName: text})}
                            returnKeyType='done'
                            multiline={false}
                        />
                        <View style={commonStyles.line_gray}/>
                        <TextInput
                            style={{
                                backgroundColor: 'white',
                                flex: 1,
                                alignItems: 'flex-end',
                                justifyContent: 'flex-end',
                                paddingLeft: 10,
                                width: width,
                                height: 48
                            }}
                            placeholder='详细地址'
                            value={this.props.address}
                            underlineColorAndroid={'transparent'}
                            textAlign='left'
                            writingDirection='rtl'
                            onChangeText={(text) => this.props.changeShopInfo({address: text})}
                            returnKeyType='done'
                            multiline={false}
                        />
                        <View style={[commonStyles.line_gray, {marginTop: 10}]}/>
                        <TouchableOpacity
                            onPress={() => this.chooseLocation()}
                            underlayColor='rgba(255,255,255,0)'>
                            <View style={[commonStyles.itembar, {paddingLeft: 10, paddingRight: 10}]}>
                                <Text style={commonStyles.itembar_txt}>位置信息</Text>
                                <View style={commonstyles.itembarRight}>
                                    <Text>{positionResult}</Text>
                                    <Image style={{width: 20, height: 15}} source={require('../../image/img_right_grey.png')}/>
                                </View>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => this.save()}
                            underlayColor='rgba(255,255,255,0)'>
                            <View style={[commonStyles.greenbtn, {marginTop: 15, marginBottom: 15}]}>
                                <Text style={commonStyles.greenbtn_txt}>保存</Text>
                            </View>
                        </TouchableOpacity>
                        <ActionSheet
                            ref={o => this.ActionSheet = o}
                            title='选择图片'
                            cancelButtonIndex={0}
                            destructiveButtonIndex={1}
                            options={['取消', '拍照', '相册选取']}
                            onPress={this.handlePress}
                        />
                    </ScrollView>
                </KeyboardAvoidingView>
            </View>
        );
    }

}

const mapStateToProps = state => ({
    token: state.mainmodel.token,
    shopName: state.shop.shopName,
    cityName: state.shop.cityName,
    address: state.shop.address,
    phone: state.shop.phone,
    shoplogo: state.shop.shoplogo,
    shopBackgroundImg: state.shop.shopBackgroundImg,
    lng: state.shop.lng,
    lat: state.shop.lat,
    notice: state.shop.notice,
    otherInfo: state.shop.otherInfo,
    brandSet: state.shop.brandSet,
    brand: state.shop.brand,
    auditStatus: state.shop.auditStatus
});

const mapDispatchToProps = dispatch => ({
    naviPush:(routerName, params) => {
        dispatch(naviPush(routerName, params))
    },
    getShopInfo: (token) => {
        dispatch(getShopInfo(token))
    },
    getAuthInfo: (token) => {
        dispatch(getAuthInfo(token))
    },
    changeShopInfo: (changedInfo) => {
        dispatch(changeShopInfo(changedInfo))
    },
    naviBack: () => {
        dispatch(naviBack());
    },
    gotoCert: (value) => {
        dispatch(gotoCert(value));
    }
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Shop);
